import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  userBean: {}, // 用户信息表
  codeMap: {}, // 代码表
  menuList: [], // 权限菜单表
  btnList: [] // 按钮权限表
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERBEAN: (state, userBean) => {
    state.userBean = userBean
  },
  SET_CODEMAP: (state, codeMap) => {
    state.codeMap = codeMap
  },
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_BTNLIST: (state, btnList) => {
    state.btnList = btnList
  }
}

const actions = {
  // user login getToken
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('token获取失败，请稍后再试')
        }

        // 设置用户姓名 码表 菜单 权限 按钮权限 用户信息等
        const { codeMap, menuList, btnList, userBean } = data
        commit('SET_NAME', userBean.fullName)
        commit('SET_CODEMAP', codeMap)
        commit('SET_MENULIST', menuList)
        commit('SET_BTNLIST', btnList)
        commit('SET_USERBEAN', userBean)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

